<?php
//+--------------------------------------------
//|描述  ws 优化 基础类库
//|--------------------------------------------
//|Created by PhpStorm.
//| Author: DRG
//+-------------------------------------------
//|Date: 2018/5/29
//| Time: 9:49
//+--------------------------------------------

class Ws{
    CONST HOST = "0.0.0.0";
    CONST PORT = 8812;
    
    public $ws = null;
    public function __construct()
    {
        $this->ws = new swoole_websocket_server(self::HOST, self::PORT);
        
        $this->ws->set(
            [
                'worker_num' => 2,
                'task_worker_num' => 2
            ]
        );
        $this->ws->on("open", [$this, 'onOpen']);
        $this->ws->on("message", [$this, 'onMessage']);
        //task   投递事件
        $this->ws->on("task", [$this, 'onTask']);
        $this->ws->on("finish", [$this, 'onFinish']);
        
        $this->ws->on("close", [$this, 'onClose']);
        $this->ws->start();
    }
    
    /**
     * 监听ws连接事件
     * @param $ws
     * @param $request
     * @author DRG
     */
    public function onOpen($ws, $request)
    {
        var_dump($request->fd);
        if($request->fd == 1) {
            //每两秒执行
            swoole_timer_tick(2000, function ($timer_id){
               echo "2s: timerId :{$timer_id}\n";
            });
        }
    }
    
    /**
     * 监听  ws消息事件
     * @param $ws
     * @param $frame
     * @author DRG
     */
    public function onMessage($ws, $frame)
    {
        echo "ser-push-message:{$frame->data}\n";
        
        //耗时任务   todo  10s
        $data = [
            'task'=>1,
            'fd'=>$frame->fd,
        ];
        //$ws->task($data);
        
        //异步的  会先执行下面的push   然后五秒后再执行这个定时器
        swoole_timer_after(5000, function () use ($ws, $frame) {
           echo "5s-after\n";
           $ws->push($frame->fd, "server-time-after:");
        });
        $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
        
    }
    
    /**
     * @param $serv
     * @param $task_id
     * @param $src_worker_id
     * @param $data
     * @author DRG
     */
    public function onTask( $serv,  $task_id,  $src_worker_id,  $data)
    {
        print_r($data);
        //模拟场景   耗时 10s
        sleep(10);
        return "on task finish";//告诉worker
    }
    
    /**
     * @param $serv
     * @param $taskId
     * @param $data    是onTask  中return的内容
     * @author DRG
     */
    public function onFinish($serv, $taskId, $data)
    {
        echo "taskId: {$taskId}\n";
        echo "finish-data-success: {$data}\n";
    }
    /**
     * 关闭连接
     * @param $ws
     * @param $fd
     * @author DRG
     */
    public function onClose($ws, $fd)
    {
        echo "clientid:{$fd}";
    }
}

$obj = new Ws();